using System;
using System.Linq;
using System.Linq.Expressions;

namespace Magiq.Insert {
  public class QueryableInsert<F, T> : IQueryableInsert<F, T>  where T : class {
    private readonly IInsertProvider provider;

    public QueryableInsert(IQueryable<F> queryable, Expression<Func<F, T>> newValueExpression) {
      Source = queryable;
      NewExpression = newValueExpression;
      provider = Magiq.For(queryable).GetInsertProvider();
    }

    #region IQueryableInsert<F,T> Members

    public Expression<Func<F, T>> NewExpression { get; private set; }

    public IQueryable<F> Source { get; private set; }

    public int Into(IQueryable<T> destination) {
      Destination = destination;
      return provider.Execute(this);
    }

    public int Into(IQueryable destination) {
      if (!destination.ElementType.IsAssignableFrom(typeof (T)))
        throw new InvalidOperationException("Type " + typeof (T).FullName + " should inherit from " +
                                            destination.ElementType.FullName);

      Destination = destination;
      return provider.Execute(this);
    }

    public IQueryable Destination { get; private set; }

    #endregion
  }
}